package com.example.service.impl;

import com.example.entity.SysTask;
import com.example.handler.SysTaskHandler;
import com.example.service.SysTaskDispatcherService;
import com.example.service.SysTaskService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.example.service.SysTaskService.FAILURES_COUNT;

@Service
public class SysTaskDispatcherServiceImpl implements SysTaskDispatcherService {

    @Resource
    private SysTaskService sysTaskService;

    @Resource
    private List<SysTaskHandler> list = new ArrayList<>();

    @Override
    public void updateAndHandler(SysTask sysTask) {
        for (SysTaskHandler sysTaskHandler : list) {
            if (sysTaskHandler.isMatch(sysTask) && !sysTask.getSuccess()) {
                try {
                    sysTaskHandler.handler(sysTask);
                    sysTask.setSuccess(Boolean.TRUE);
                    sysTaskService.saveOrUpdate(sysTask);
                } catch (Exception e) {
                    sysTask.setRunTime(System.nanoTime());
                    sysTask.setErrorMessage(e.getMessage());
                    sysTask.setFailures(sysTask.getFailures() + 1);
                    sysTask.setSuccess(Boolean.FALSE);
                    sysTask.setQueueType(Boolean.FALSE);
                    sysTaskService.saveOrUpdate(sysTask);
                    if (sysTask.getFailures() < FAILURES_COUNT) {
                        sysTaskService.dispatcherToErrorQueue(sysTask);
                    }
                }
            }
        }
    }

}
